package jsyf.oa.service.system;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.constant.Const;
import jsyf.com.constant.WechatConstant;
import jsyf.com.util.BaseUtils;
import jsyf.com.util.DateUtils;
import jsyf.oa.dao.system.*;
import jsyf.oa.entity.system.WechatShareEntity;
import jsyf.oa.facade.system.WechatShareFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by WHH-PC on 2018/1/12.
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class WechatShareService implements WechatShareFacade {

    @Autowired
    private WechatShareDao wechatShareDao;
    @Autowired
    private WechatShareDetailDao wechatShareDetailDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private SignInDao signInDao;
    @Autowired
    private CompanyDao companyDao;

    @Override
    public String save(String jsonData) {
        WechatShareEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), WechatShareEntity.class);
        Integer rows;
        if (StringUtils.isBlank(entity.getId())&&StringUtils.isNotEmpty(entity.getLinkUrl())&&StringUtils.isNotEmpty(entity.getImageUrl())&&StringUtils.isNotEmpty(entity.getName())) {
            rows = wechatShareDao.add(entity);
        } else {
            WechatShareEntity wechatShareEntity = wechatShareDao.getById(entity.getId());
            wechatShareEntity.setName(entity.getName());
            wechatShareEntity.setLinkUrl(entity.getLinkUrl());
            wechatShareEntity.setImageUrl(entity.getImageUrl());
            wechatShareEntity.setRemark(entity.getRemark());
            rows = wechatShareDao.update(wechatShareEntity);
        }
        return rows == 0 ? "" : entity.getId();
    }

    @Override
    public List<JSONObject> getWechatShare(String shareDate, String userId, String companyId) {
        //查询某天需要分享的链接
        JSONObject jsonUser = userDao.getViewJSONById(userId);
        String compId = "";
        if (!StringUtils.isBlank(companyId)) {
            compId = companyId;
        } else if (jsonUser != null) {
            compId = jsonUser.get("companyId").toString();
        }
        List<JSONObject> list = wechatShareDao.getWechatShareList(shareDate, compId);

        for (Integer i = 0; i < list.size(); i++) {
            String shareId = list.get(i).get("id").toString();
            String conditionA = "";
            if (StringUtils.isNotEmpty(shareDate)) {
                conditionA += "AND DATE_FORMAT(CREATE_TIME,'%Y-%m-%d')=? ";
            }
            if (StringUtils.isNotEmpty(userId)) {
                conditionA += "AND USER_ID=? ";
            }
            conditionA += "AND WECHAT_SHARE_ID=? ";
            list.get(i).put("morningFlag", false);
            list.get(i).put("noonFlag", false);
            list.get(i).put("nightFlag", false);
            //查询某人某天对某个链接的分享记录
            List<JSONObject> detailList = wechatShareDetailDao.getJSONListByCondition(conditionA, new Object[]{shareDate, userId, shareId});
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (Integer j = 0; j < detailList.size(); j++) {
                //Date createTime = detailList.get(j).getDate("createTime");
                String _createTime = detailList.get(j).getString("createTime");
                Date createTime = null;
                try {
                    createTime = sdf.parse(_createTime);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                //上午是否分享
                if (DateUtils.isInDate(createTime, WechatConstant.morningStart, WechatConstant.morningEnd)) {
                    list.get(i).put("morningFlag", true);
                }
                //中午是否分享
                if (DateUtils.isInDate(createTime, WechatConstant.noonStart, WechatConstant.noonEnd)) {
                    list.get(i).put("noonFlag", true);
                }
                //晚上是否分享
                if (DateUtils.isInDate(createTime, WechatConstant.nightStart, WechatConstant.nightEnd)) {
                    list.get(i).put("nightFlag", true);
                }
            }
        }
        return list;
    }

    @Override
    public String delById(String id) {
        int flag = this.wechatShareDao.removeById(id);
        if (Const.INT_ONE == flag) {
            return BaseUtils.succsessObjRespond("删除成功");
        }
        return BaseUtils.errorrRespond("删除失败");
    }

    @Override
    public String saveTodayWechatShare(String companyId, String userId, String shareDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd ");
        Date date = null;
        try {
            date = formatter.parse(shareDate + " 00:00:00");
        } catch (Exception e) {
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, -1);
        String proShareDate = DateUtils.parse(calendar.getTime(), "yyyy-MM-dd");
        //查询某天前一天微信分享链接
        List<JSONObject> shareList = wechatShareDao.getJSONListByCondition(" AND SHARE_DATE = ? AND COMPANY_ID = ? ", new Object[]{proShareDate, companyId});
        if (shareList.size() > 0) {
            //删除某天的链接
            wechatShareDao.removeByCondition(" AND SHARE_DATE = ? AND COMPANY_ID = ? ", new String[]{shareDate, companyId});
            for (Integer i = 0; i < shareList.size(); i++) {
                System.out.println(shareList.get(i).get("remark").toString());
                WechatShareEntity shareEntity = new WechatShareEntity();
                shareEntity.setCompanyId(companyId);
                shareEntity.setShareDate(shareDate);
                shareEntity.setName(shareList.get(i).get("name").toString());
                shareEntity.setLinkUrl(shareList.get(i).get("linkUrl").toString());
                shareEntity.setImageUrl(shareList.get(i).get("imageUrl").toString());
                shareEntity.setForwardNumber(Integer.valueOf(shareList.get(i).get("forwardNumber").toString()));
                shareEntity.setCreateUserId(shareList.get(i).get("createUserId").toString());
                shareEntity.setRemark(shareList.get(i).get("remark").toString());
                wechatShareDao.add(shareEntity);
            }
        }
        return "";
    }

    /**
     * 微信转发汇总
     *
     * @param jsonObject
     * @return
     */
    @Override
    public JSONObject getWechatShareTotal(JSONObject jsonObject) {
        String userId = jsonObject.get("userId").toString();
        String shareMonth = jsonObject.get("shareMonth").toString();
        System.out.println(userId+shareMonth);
        Calendar calendar = Calendar.getInstance();
        String today = DateUtils.parse(calendar.getTime(), "yyyy-MM-dd");
        JSONObject userJson = userDao.getViewJSONListByCondition(" AND id = ? AND main = 1 ",new Object[]{userId}).get(0);
        String companyId = userJson.get("companyId").toString();
        String companyName = userJson.get("companyName").toString();
        JSONObject result = new JSONObject();
        if("201712161613432EAF27DBCCB7D0E6CA".equals(companyId)){
            //当天
            List<JSONObject> companyList = wechatShareDao.getCompanyList();
            Integer todayForwardTotal  = 0;
            Integer todayFinishForwardTotal = 0;
            Integer todayNoForwardTotal = 0;
            for (Integer i = 0; i < companyList.size(); i++) {
                JSONObject companyJsonObject = wechatShareDao.getShareByCompanyId(companyList.get(i).get("companyId").toString(), "1", shareMonth);
                todayForwardTotal += Integer.valueOf(companyJsonObject.get("forward").toString());
                todayFinishForwardTotal += Integer.valueOf(companyJsonObject.get("finishForward").toString());
                //Integer noForward = Integer.valueOf(companyJsonObject.get("forward").toString()) - Integer.valueOf(companyJsonObject.get("finishForward").toString());

            }
            Integer _noForward = todayForwardTotal - todayFinishForwardTotal >= 0 ? todayForwardTotal - todayFinishForwardTotal : 0;
            todayNoForwardTotal += _noForward;

            result.put("todayForward", todayForwardTotal);
            result.put("todayFinishForward", todayFinishForwardTotal);
            result.put("todayNoForward",todayNoForwardTotal);
            //某个月
            Integer monthForwardTotal  = 0;
            Integer monthFinishForwardTotal = 0;
            Integer monthNoForwardTotal = 0;
            for (Integer i = 0; i < companyList.size(); i++) {
                JSONObject companyJsonObject = wechatShareDao.getShareByCompanyId(companyList.get(i).get("companyId").toString(), "0", shareMonth);
                monthForwardTotal += Integer.valueOf(companyJsonObject.get("forward").toString());
                monthFinishForwardTotal += Integer.valueOf(companyJsonObject.get("finishForward").toString());
                Integer noForward = Integer.valueOf(companyJsonObject.get("forward").toString()) - Integer.valueOf(companyJsonObject.get("finishForward").toString());
                monthNoForwardTotal += noForward;
            }
            result.put("monthForward", monthForwardTotal);
            result.put("monthFinishForward", monthFinishForwardTotal);
            result.put("monthNoForward", monthNoForwardTotal);
        }
        else {
            result = wechatShareDao.getWechatShareTotal(userJson.get("roleName").toString(), shareMonth, today, userJson.get("departId").toString(), companyId, userId);
            Integer todayForward = Integer.valueOf(result.get("todayForward").toString());
            Integer todayFinishForward = Integer.valueOf(result.get("todayFinishForward").toString());
            Integer monthForward = Integer.valueOf(result.get("monthForward").toString());
            Integer monthFinishForward = Integer.valueOf(result.get("monthFinishForward").toString());
            result.put("todayNoForward", todayForward - todayFinishForward < 0 ? 0 : todayForward - todayFinishForward);
            result.put("monthNoForward", monthForward - monthFinishForward < 0 ? 0 : monthForward - monthFinishForward);
        }

        return result;
    }

    /**
     * 某个月的分享链接
     *
     * @param jsonData
     * @return
     */
    @Override
    public List<JSONObject> getMonthShareList(JSONObject jsonData) {
        String userId = jsonData.get("userId").toString();
        String companyId = jsonData.get("companyId").toString();
        String shareMonth = jsonData.get("shareMonth").toString();
        //返回的集合
        List<JSONObject> dayList = new ArrayList<>();
        //已过去的天数
        List<String> arrayDayList = new ArrayList<>();
        //当前日期
        Calendar c = Calendar.getInstance();
        String month = DateUtils.parse(c.getTime(), "yyyy-MM");
        if (shareMonth.equals(month)) {
            //当月，获取当天是本月的第几天
            Integer days = c.get(Calendar.DAY_OF_MONTH);
            for (Integer i = days; i >= 1; i--) {
                arrayDayList.add(shareMonth + "-" + (i < 10 ? ("0" + i) : i));
            }
        } else {
            //非当月，获取某月最后一天
            Integer lastDay = DateUtils.getLastDayOfMonth(Integer.valueOf(shareMonth.split("-")[0]), Integer.valueOf(shareMonth.split("-")[1]));
            for (Integer i = lastDay; i >= 1; i--) {
                arrayDayList.add(shareMonth + "-" + (i < 10 ? ("0" + i) : i));
            }
        }

        //分享信息赋值
        for (Integer i = 0; i < arrayDayList.size(); i++) {
            String day = arrayDayList.get(i);
            //获取每天分享链接列表
            List<JSONObject> list = wechatShareDao.getJSONListByCondition(" AND COMPANY_ID = ? AND SHARE_DATE = ?", new Object[]{companyId, day});
            for (Integer j = 0; j < list.size(); j++) {
                JSONObject objResult = new JSONObject();
                objResult.put("shareDate", day);
                objResult.put("name", list.get(j).get("name").toString());
                objResult.put("forwardNumber", list.get(j).get("forwardNumber").toString());
                objResult.put("morningFlag", false);
                objResult.put("noonFlag", false);
                objResult.put("nightFlag", false);
                //查询某人某天对某个链接的分享记录
                List<JSONObject> detailList = wechatShareDetailDao.getJSONListByCondition(" AND DATE_FORMAT(CREATE_TIME,'%Y-%m-%d')=? AND USER_ID=? AND WECHAT_SHARE_ID=? ", new Object[]{day, userId, list.get(j).get("id").toString()});
                for (Integer k = 0; k < detailList.size(); k++) {
                    Date createTime = detailList.get(k).getDate("createTime");
                    //上午是否分享
                    if (DateUtils.isInDate(createTime, WechatConstant.morningStart, WechatConstant.morningEnd)) {
                        objResult.put("morningFlag", true);
                    }
                    //中午是否分享
                    if (DateUtils.isInDate(createTime, WechatConstant.noonStart, WechatConstant.noonEnd)) {
                        objResult.put("noonFlag", true);
                    }
                    //晚上是否分享
                    if (DateUtils.isInDate(createTime, WechatConstant.nightStart, WechatConstant.nightEnd)) {
                        objResult.put("nightFlag", true);
                    }
                }
                dayList.add(objResult);
            }
        }
        return dayList;
    }

    /**
     * 大区经理：大区、小区微信分享列表
     *
     * @return
     */
    @Override
    public List<JSONObject> getShareRegionList(JSONObject jsonObject) {
        String userId = jsonObject.get("userId").toString();
        String shareMonth = jsonObject.get("shareMonth").toString();
        String isToday = jsonObject.get("isToday").toString();
        //当前日期
        Calendar c = Calendar.getInstance();
        JSONObject jsonUser = userDao.getViewJSONById(userId);
        List<JSONObject> regionlist = signInDao.getRegionListByBigRegionDepartId(jsonUser.get("departId").toString());
        //返回的集合
        List<JSONObject> list = new ArrayList<>();
        for (Integer i = 0; i < regionlist.size(); i++) {
            JSONObject objResult = new JSONObject();
            String regionId = regionlist.get(i).get("regionId").toString();
            String managerId = regionlist.get(i).get("managerId").toString();
            String managerRoleName = regionlist.get(i).get("managerRoleName").toString();
            String managerName = regionlist.get(i).get("managerName").toString();
            String regionName = regionlist.get(i).get("regionName").toString();
            objResult.put("regionId", regionId);
            objResult.put("regionName", regionName);
            objResult.put("userId", managerId);
            objResult.put("roleName", managerRoleName);
            objResult.put("name", managerName);
            //获取某人某天或某月分享信息
            JSONObject result = wechatShareDao.getShareByUserId(managerId, isToday, shareMonth);
            Integer forward = Integer.valueOf(result.get("forward").toString());
            Integer finishForward = Integer.valueOf(result.get("finishForward").toString());
            objResult.put("forward", forward);
            objResult.put("finishForward", finishForward);
            Integer noForward = forward - finishForward >= 0 ? forward - finishForward : 0;
            objResult.put("noForward", noForward);
            objResult.put("contacts",result.getString("contacts"));
            list.add(objResult);
        }
        return list;
    }

    /**
     * 区域支持微信转发列表
     *
     * @param jsonObject
     * @return
     */
    @Override
    public List<JSONObject> getShareSupportRegionList(JSONObject jsonObject) {
        String userId = jsonObject.get("userId").toString();
        String isToday = jsonObject.get("isToday").toString();
        String shareMonth = jsonObject.get("shareMonth").toString();
        //返回的集合
        List<JSONObject> list = new ArrayList<>();

        //获取区域支持负责的所有区域
        List<JSONObject> regionList = signInDao.getSupportRegionList(userId);
        for (JSONObject valJson : regionList.stream().filter(x -> x.get("parentId").toString().equals("0")).collect(Collectors.toList())) {
            if (valJson.get("regionName").equals("大客户")) {
                continue;
            }
            for (JSONObject regionJson : regionList.stream().filter(x -> x.get("parentId").toString().equals(valJson.get("regionId")) || x.get("regionId").toString().equals(valJson.get("regionId"))).collect(Collectors.toList())) {
                JSONObject json = new JSONObject();
                String uid = regionJson.get("userId").toString();
                if (regionJson.get("parentId").toString().equals("0")) {
                    json.put("departName", regionJson.get("regionName").toString());
                } else if (!regionJson.get("parentId").toString().equals("")) {
                    json.put("departName", regionList.stream().filter(x -> x.get("regionId").toString().equals(regionJson.get("parentId").toString())).collect(Collectors.toList()).get(0).get("regionName").toString());
                }
                json.put("regionName", regionJson.get("regionName").toString());
                json.put("roleName", regionJson.get("parentId").toString().equals("0") ? "大区经理" : "区域经理");
                json.put("name", !regionJson.get("userName").toString().equals("") ? regionJson.get("userName").toString() : "空缺");
                json.put("userId", uid);
                if (StringUtils.isNotEmpty(uid)) {
                    //获取某人某天或某月分享信息
                    JSONObject result = wechatShareDao.getShareByUserId(uid, isToday, shareMonth);

                    Integer forward = Integer.valueOf(result.get("forward").toString());
                    Integer finishForward = Integer.valueOf(result.get("finishForward").toString());
                    json.put("forward", forward);
                    json.put("finishForward", finishForward);
                    Integer noForward = forward - finishForward >= 0 ? forward - finishForward : 0;
                    json.put("noForward", noForward);
                    json.put("contacts",result.getString("contacts"));
                }
                list.add(json);
            }
        }
        return list;
    }

    /**
     * 销售管理经理微信转发列表
     *
     * @param jsonObject
     * @return
     */
    @Override
    public List<JSONObject> getShareSalerManagerList(JSONObject jsonObject) {
        String companyId = jsonObject.get("companyId").toString();
        String isToday = jsonObject.get("isToday").toString();
        String shareMonth = jsonObject.get("shareMonth").toString();
        //返回的集合
        List<JSONObject> list = new ArrayList<>();
        List<JSONObject> regionList = wechatShareDao.getRegionAndUserListByCompany(companyId);
        //大区转发
        for (JSONObject valJson : regionList.stream().filter(x -> x.get("parentId").toString().equals("0")).collect(Collectors.toList())) {
            if (valJson.get("regionName").equals("大客户")) {
                continue;
            }
            for (JSONObject regionJson : regionList.stream().filter(x -> x.get("parentId").toString().equals(valJson.get("regionId")) || x.get("regionId").toString().equals(valJson.get("regionId"))).collect(Collectors.toList())) {
                JSONObject json = new JSONObject();
                String uid = regionJson.get("userId").toString();
                if (regionJson.get("parentId").toString().equals("0")) {
                    json.put("departName", regionJson.get("regionName").toString());
                } else if (!regionJson.get("parentId").toString().equals("")) {
                    json.put("departName", regionList.stream().filter(x -> x.get("regionId").toString().equals(regionJson.get("parentId").toString())).collect(Collectors.toList()).get(0).get("regionName").toString());
                }
                json.put("regionName", regionJson.get("regionName").toString());
                json.put("roleName", regionJson.get("parentId").toString().equals("0") ? "大区经理" : "区域经理");
                json.put("name", !regionJson.get("userName").toString().equals("") ? regionJson.get("userName").toString() : "空缺");
                json.put("userId", uid);
                if (StringUtils.isNotEmpty(uid)) {
                    //获取某人某天或某月分享信息
                    JSONObject result = wechatShareDao.getShareByUserId(uid, isToday, shareMonth);

                    Integer forward = Integer.valueOf(result.get("forward").toString());
                    Integer finishForward = Integer.valueOf(result.get("finishForward").toString());
                    json.put("forward", forward);
                    json.put("finishForward", finishForward);
                    Integer noForward = forward - finishForward >= 0 ? forward - finishForward : 0;
                    json.put("noForward", noForward);
                    json.put("contacts",result.getString("contacts"));
                }
                list.add(json);
            }
        }
        return list;
    }

    /**
     * 集团管理微信转发
     *
     * @param jsonObject
     * @return
     */
    @Override
    public List<JSONObject> getShareCompanyList(JSONObject jsonObject) {
        String shareMonth = jsonObject.get("shareMonth").toString();
        String isToday = jsonObject.get("isToday").toString();
        //返回的集合
        List<JSONObject> list = new ArrayList<>();
        //所有公司
        List<JSONObject> companyList = wechatShareDao.getCompanyList();
        for (Integer i = 0; i < companyList.size(); i++) {
            String companyId = companyList.get(i).get("companyId").toString();
            String companyName = companyList.get(i).get("companyName").toString();
            String managerName = companyList.get(i).get("managerName").toString();
            String salerMangerName = companyList.get(i).get("salerManagerName").toString();
            if (StringUtils.isBlank(managerName) || "".equals(managerName)) {
                managerName = salerMangerName;
            }
            JSONObject jsonResult = new JSONObject();
            jsonResult.put("companyName", companyName);
            jsonResult.put("companyId", companyId);
            jsonResult.put("managerName", managerName);
            JSONObject companyJsonObject = wechatShareDao.getShareByCompanyId(companyId, isToday, shareMonth);
            jsonResult.put("forward", Integer.valueOf(companyJsonObject.get("forward").toString()));
            jsonResult.put("finishForward", Integer.valueOf(companyJsonObject.get("finishForward").toString()));
            Integer noForward = Integer.valueOf(companyJsonObject.get("forward").toString()) - Integer.valueOf(companyJsonObject.get("finishForward").toString());
            if (noForward <0){
                noForward = 0;
            }
            jsonResult.put("noForward", noForward);
            list.add(jsonResult);
        }
        return list;
    }

    @Override
    public JSONObject getShareByCompanyId(JSONObject jsonObject) {
        String shareMonth = jsonObject.get("shareMonth").toString();
        String isToday = jsonObject.get("isToday").toString();
        String companyId = jsonObject.get("companyId").toString();
        JSONObject jsonResult = new JSONObject();
        JSONObject companyJsonObject = wechatShareDao.getShareByCompanyId(companyId, isToday, shareMonth);
        jsonResult.put("forward", Integer.valueOf(companyJsonObject.get("forward").toString()));
        jsonResult.put("finishForward", Integer.valueOf(companyJsonObject.get("finishForward").toString()));
        Integer noForward = Integer.valueOf(companyJsonObject.get("forward").toString()) - Integer.valueOf(companyJsonObject.get("finishForward").toString());
        if (noForward < 0){ noForward = 0;}
        jsonResult.put("noForward", noForward);
        return jsonResult;
    }


}
